package com.warmlight.voicepacket.ui.user.usercenter;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.CreatePlaylistActivity;
import com.warmlight.voicepacket.MyPlaylistEditActivity;
import com.warmlight.voicepacket.PlayDetailMineActivity;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.MyCoverListOnNetAdapter;
import com.warmlight.voicepacket.adapter.MyPlaylistAdapter;
import com.warmlight.voicepacket.base.BaseFragment;
import com.warmlight.voicepacket.data.UserCenterData;
import com.warmlight.voicepacket.data.eventbus.Login;
import com.warmlight.voicepacket.data.eventbus.NotifyMyPlaylist;
import com.warmlight.voicepacket.dbdata.DBFloatPlayListDetail;
import com.warmlight.voicepacket.dbdata.DBFloatPlaylist;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDaoHelp;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDetailDaoHelp;
import com.warmlight.voicepacket.http.Callback;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.ui.CreateNetPlaylistActivity;
import com.warmlight.voicepacket.ui.user.MyCoverDetailOnNetActivity;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.Call;

import static com.warmlight.voicepacket.db.VoicePacketDBHelper.LIST_ID;
import static com.warmlight.voicepacket.fragment.PlaylistFragment.LOCAL;

public class MyCoverFragment extends BaseFragment {

    private MyCoverListOnNetAdapter adapter;
    private ListView lv_my_playlist;
    private LinearLayout linearLayout;
    private MyPlaylistAdapter mMyPlaylistAdapter;
    private TextView tv_no_cover;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        View view = inflater.inflate(R.layout.fragment_my_cover,container,false);
        return view;
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        lv_my_playlist = view.findViewById(R.id.lv_my_playlist);
        tv_no_cover = view.findViewById(R.id.tv_no_cover);
        initView();
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(NotifyMyPlaylist data){
        if (SPUtils.isLogined()){
            refresh();
        }else {
            queryMyList();
        }
    }

    private void refresh(){
        loadData();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void xxx(Login login){
        initData();
    }


    private void initData() {
        if (SPUtils.isLogined()) {//登录并上传网络
//            if (ltn) {
            adapter = new MyCoverListOnNetAdapter(getContext(), new ArrayList<UserCenterData.ListBean>());
            lv_my_playlist.setAdapter(adapter);
            lv_my_playlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                    if (position == 0){
                        return;
                    }
                    position --;
                    String audio_num = adapter.getItem(position).getAudio_num();
                    int num = Integer.valueOf(audio_num);
                    if (num > 0){
                        Intent intent = new Intent(getContext(), MyCoverDetailOnNetActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable(LOCAL,(DBFloatPlaylist)mPlaylist.get(position));
//                    intent.putExtras(bundle);
                        intent.putExtra("cover_id",adapter.getItem(position).getId());
                        //我的播单点击
//                    MobclickAgent.onEvent(getActivity().getApplicationContext(), MobClickHelper.CLOT_FEED,mPlaylist.get(position).getList_name());
//                    HashMap<String,Object> temp = new HashMap<>();
//                    temp.put("我的播单点击",mPlaylist.get(position).getList_name().toString());
//                    ZhugeSDK.getInstance().track(getActivity().getApplicationContext(),MobClickHelper.CLOT_FEED,temp);

                        getContext().startActivity(intent);
                    }
                    try {
                        MobclickAgent.onEvent(getContext(),MobClickHelper.profile_clot_bat,adapter.getItem(position).getName());
                    }catch (Exception e){

                    }

                }
            });
//            }else{
//                loadLocal();
//            }
//            iv_add_cover.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    //我的播单创建
//                    MobclickAgent.onEvent(getActivity().getApplicationContext(), MobClickHelper.CLOT_BUILD);
//                    ZhugeSDK.getInstance().track(getActivity().getApplicationContext(),MobClickHelper.CLOT_BUILD);
//
//                    getActivity().startActivity(new Intent(getActivity(), CreateNetPlaylistActivity.class));
//                }
//            });
            loadData();
        } else {

            loadLocal();
        }

    }

    private void loadData(){
        String url = HttpConfig.USER_CENTER;
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("auth_key", SPUtils.getLoginAuthKey());
        HttpClient.post(url, treeMap, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, String response) {
//                String s = response.body().string();
                ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                if (listMapByJson.size()>0){
                    Map<String, String> map = listMapByJson.get(0);
                    if (TextUtils.equals("200",map.get("code"))){
                        String data = map.get("data");

                        final UserCenterData userCenterData = new Gson().fromJson(data, UserCenterData.class);
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                initData((ArrayList<UserCenterData.ListBean>) userCenterData.getList());
                            }
                        });


//                        ArrayList<Map<String, String>> dataList = JSONUtils.getListMapByJson(data);
//                        Map<String, String> dataMap = dataList.get(0);
//                        String author = dataMap.get("author");
//                        String list = dataMap.get("list");
                    }else{
//                        SPUtils.clearLogin();
//                        getActivity().runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                initData();
//                            }
//                        });
                    }
                }
            }
        });
    }


    private void loadLocal(){
        mMyPlaylistAdapter = new MyPlaylistAdapter(getActivity().getApplicationContext(),new ArrayList<DBFloatPlaylist>());
        lv_my_playlist.setAdapter(mMyPlaylistAdapter);
        lv_my_playlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                if (position == 0){
                    return;
                }
                position --;
                Intent intent = new Intent(getContext(), PlayDetailMineActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(LOCAL,(DBFloatPlaylist)mMyPlaylistAdapter.getItem(position));
                intent.putExtras(bundle);

                //我的播单点击

                getContext().startActivity(intent);
            }
        });

//        iv_add_cover.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //我的播单创建
//                MobclickAgent.onEvent(getActivity().getApplicationContext(), MobClickHelper.CLOT_BUILD);
//                ZhugeSDK.getInstance().track(getActivity().getApplicationContext(),MobClickHelper.CLOT_BUILD);
//
//                getActivity().startActivity(new Intent(getActivity(), CreatePlaylistActivity.class));
//            }
//        });
        queryMyList();
    }

    private void queryMyList(){
        if(mMyPlaylistAdapter!=null){
            List<DBFloatPlaylist> mPlaylist = DBFloatPlayListDaoHelp.loadAll(getActivity());
            headView(mPlaylist);
//            mPlaylist.remove(0);
            mMyPlaylistAdapter.setList(mPlaylist);
            if (mPlaylist.size() == 0){
                tv_no_cover.setVisibility(View.VISIBLE);
                tv_no_cover.setText("没有内容，快去首页看看吧~");
            }else{
                tv_no_cover.setVisibility(View.GONE);
            }
        }
    }

    private void initView() {
        linearLayout = new LinearLayout(getContext());
        AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setLayoutParams(lp);
        lv_my_playlist.addHeaderView(linearLayout);
    }

    private void headView(final UserCenterData.ListBean data){
        linearLayout.removeAllViews();
        ImageView iv_myplaylist;
        ImageView iv_myplaylist_edit;
        TextView tv_myplaylist_title;
        TextView tv_myplaylist_count;
        ImageView iv_cover;
        View convertView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_my_cover_header,null);
        tv_myplaylist_title = (TextView) convertView.findViewById(R.id.tv_myplaylist_title);
        tv_myplaylist_count = (TextView) convertView.findViewById(R.id.tv_myplaylist_count);
        iv_myplaylist_edit = (ImageView) convertView.findViewById(R.id.iv_myplaylist_edit);
        iv_myplaylist = (ImageView) convertView.findViewById(R.id.iv_myplaylist);
        iv_cover = (ImageView) convertView.findViewById(R.id.iv_cover);

//        final UserCenterData.ListBean data = list.get(0);
        if (data != null) {
            tv_myplaylist_title.setText(data.getName());
            tv_myplaylist_count.setText(data.getAudio_num() + "个");
            if ("我的最爱".equals(data.getName())) {
                iv_cover.setVisibility(View.VISIBLE);
            } else {
                iv_cover.setVisibility(View.GONE);
            }

            String avator = data.getAvator();
            RequestOptions options = new RequestOptions();
            options.placeholder(R.drawable.icon_iv_fail);
            Glide.with(getContext()).asBitmap().load(avator).apply(options).into(iv_myplaylist);
//        if("0".equals(data.getAudio_num())){
//            Glide.with(mContext).load(R.drawable.icon_iv_fail).asBitmap().dontAnimate().into(holder.iv_myplaylist);
//        }else{
////            List<DBFloatPlayListDetail> listAudios = DBHelper.getInstance(mContext).queryAudiosByListId(data.get_id());
//            List<DBFloatPlayListDetail> listAudios =  DBFloatPlayListDetailDaoHelp.queryBuilder(mContext,data.getId()+"");
//            if(listAudios!=null && listAudios.size()>0){
//                String url = listAudios.get(0).getAudio_ps();
//                Glide.with(mContext).load(TextUtils.isEmpty(url) ? R.drawable.icon_iv_fail : url).asBitmap().dontAnimate().into(holder.iv_myplaylist);
//            }else {
//                Glide.with(mContext).load(R.drawable.icon_iv_fail).asBitmap().dontAnimate().into(holder.iv_myplaylist);
//            }
//
//        }

            //如果播单名字是"我的最爱"则隐藏"更多"点点点按钮
            if ("我的最爱".equals(data.getName().trim())) {
                iv_myplaylist_edit.setVisibility(View.INVISIBLE);
            } else {
                iv_myplaylist_edit.setVisibility(View.VISIBLE);
            }

            iv_myplaylist_edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(getContext(), MyPlaylistEditActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("cover_net", data);
                    intent.putExtras(bundle);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
            });

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String audio_num = data.getAudio_num();
                    int num = Integer.valueOf(audio_num);
                    if (num > 0) {
                        Intent intent = new Intent(getContext(), MyCoverDetailOnNetActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putSerializable(LOCAL,(DBFloatPlaylist)mPlaylist.get(position));
//                    intent.putExtras(bundle);
                        intent.putExtra("cover_id", data.getId());
                        //我的播单点击
//                    MobclickAgent.onEvent(getActivity().getApplicationContext(), MobClickHelper.CLOT_FEED,mPlaylist.get(position).getList_name());
//                    HashMap<String,Object> temp = new HashMap<>();
//                    temp.put("我的播单点击",mPlaylist.get(position).getList_name().toString());
//                    ZhugeSDK.getInstance().track(getActivity().getApplicationContext(),MobClickHelper.CLOT_FEED,temp);

                        getContext().startActivity(intent);
                    }
                }
            });

            ImageView iv_add_cover = convertView.findViewById(R.id.iv_add_cover);
            iv_add_cover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //我的播单创建
                    MobclickAgent.onEvent(getActivity().getApplicationContext(), MobClickHelper.CLOT_BUILD);
                    ZhugeSDK.getInstance().track(getActivity().getApplicationContext(), MobClickHelper.CLOT_BUILD);

                    getActivity().startActivity(new Intent(getActivity(), CreateNetPlaylistActivity.class));
                }
            });
            linearLayout.addView(convertView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        }
    }



    private void initData(ArrayList<UserCenterData.ListBean> data) {
        UserCenterData.ListBean dd = null;
        for (int i=0;i<data.size();i++){
            UserCenterData.ListBean listBean = data.get(i);
            if (TextUtils.equals("我的最爱",listBean.getName())){
                dd = listBean;
                data.remove(i);
                break;
            }
        }

        headView(dd);
        adapter.setList(data);

        if (data.size() == 0){
            tv_no_cover.setVisibility(View.VISIBLE);
            tv_no_cover.setText("没有内容，快去首页看看吧~");
        }else{
            tv_no_cover.setVisibility(View.GONE);
        }

    }

    /**
     * ======================================= 本地播单  =============================================================
     * @param list
     */

    private void headView(List<DBFloatPlaylist> list){
        linearLayout.removeAllViews();
        ImageView iv_myplaylist;
        ImageView iv_myplaylist_edit;
        TextView tv_myplaylist_title;
        TextView tv_myplaylist_count;
        ImageView iv_cover;
        View convertView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_my_cover_header,null);
        tv_myplaylist_title = (TextView) convertView.findViewById(R.id.tv_myplaylist_title);
        tv_myplaylist_count = (TextView) convertView.findViewById(R.id.tv_myplaylist_count);
        iv_myplaylist_edit = (ImageView) convertView.findViewById(R.id.iv_myplaylist_edit);
        iv_myplaylist = (ImageView) convertView.findViewById(R.id.iv_myplaylist);
        iv_cover = (ImageView) convertView.findViewById(R.id.iv_cover);
        DBFloatPlaylist data = null;
        for (int i=0;i<list.size();i++){
            DBFloatPlaylist dbFloatPlaylist = list.get(i);
            if (TextUtils.equals("我的最爱",dbFloatPlaylist.getList_name())){
                data = dbFloatPlaylist;
                list.remove(i);
                break;
            }
        }

        if (data != null) {


            tv_myplaylist_title.setText(data.getList_name());
            tv_myplaylist_count.setText(data.getList_count() + "个");
            if ("我的最爱".equals(data.getList_name())) {
                iv_cover.setVisibility(View.VISIBLE);
            } else {
                iv_cover.setVisibility(View.GONE);
            }
            RequestOptions options = new RequestOptions();
            options.dontAnimate();
            if ("0".equals(data.getList_count())) {
                Glide.with(getContext()).asBitmap().load(R.drawable.icon_iv_fail).apply(options).into(iv_myplaylist);
            } else {
//            List<DBFloatPlayListDetail> listAudios = DBHelper.getInstance(mContext).queryAudiosByListId(data.get_id());
                List<DBFloatPlayListDetail> listAudios = DBFloatPlayListDetailDaoHelp.queryBuilder(getContext(), data.getId() + "");
                if (listAudios != null && listAudios.size() > 0) {
                    String url = listAudios.get(0).getAudio_ps();
                    Glide.with(getContext()).asBitmap().load(TextUtils.isEmpty(url) ? R.drawable.icon_iv_fail : url).apply(options).into(iv_myplaylist);
                } else {
                    Glide.with(getContext()).asBitmap().load(R.drawable.icon_iv_fail).apply(options).into(iv_myplaylist);
                }

            }

            //如果播单名字是"我的最爱"则隐藏"更多"点点点按钮
            if ("我的最爱".equals(data.getList_name().trim())) {
                iv_myplaylist_edit.setVisibility(View.INVISIBLE);
            } else {
                iv_myplaylist_edit.setVisibility(View.VISIBLE);
            }

            final DBFloatPlaylist finalData = data;
            iv_myplaylist_edit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                mTemp = (DBFloatPlaylist) mList.get(position);
                    Intent intent = new Intent(getContext(), MyPlaylistEditActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(LIST_ID, (DBFloatPlaylist) finalData);
                    intent.putExtras(bundle);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                    startActivity(intent);

                }
            });

            final DBFloatPlaylist finalData1 = data;
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(getContext(), PlayDetailMineActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(LOCAL, finalData1);
                    intent.putExtras(bundle);

                    //我的播单点击

                    getContext().startActivity(intent);
                }
            });

            ImageView iv_add_cover = convertView.findViewById(R.id.iv_add_cover);

            iv_add_cover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //我的播单创建
//                MobclickAgent.onEvent(getActivity().getApplicationContext(), MobClickHelper.CLOT_BUILD);
//                ZhugeSDK.getInstance().track(getActivity().getApplicationContext(),MobClickHelper.CLOT_BUILD);

                    getActivity().startActivity(new Intent(getActivity(), CreatePlaylistActivity.class));
                }
            });
            linearLayout.addView(convertView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        }
    }


}
